package com.hotfire.template.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

public class EncodeFilter implements Filter {
	private static final Logger logger = Logger.getLogger(EncodeFilter.class);

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) servletRequest;
		try {
			String type = request.getContentType();
			String requestedWith = request.getHeader("x-requested-with");
			if (requestedWith != null && "XMLHttpRequest".equals(requestedWith) && type != null && type.startsWith("application/x-www-form-urlencoded")) {
				if (logger.isInfoEnabled()) {
					logger.info("This's ajax post.set encode is UTF-8.");
				}
				request.setCharacterEncoding("UTF-8");
				response.setCharacterEncoding("UTF-8");
				request.getParameterMap();
			} else {
				request.setCharacterEncoding("UTF-8");
				response.setContentType("text/html;charset=utf-8");
			}
		} finally {
			chain.doFilter(request, response);
		}

	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
